package spring.response.entity;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 返回Json数据对象
 * @author huangqiankun
 * 2018年12月21日下午7:27:43
 * @param <T>
 */
@Data
public class JsonResponse<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 携带数据
     */
    private T data;
    
    /**
     * 状态
     */
    private JsonResponseCode code;

    /**
     * 信息
     */
    private String msg = "";
    
    /**
     * 总数
     */
    private Long count;

	private JsonResponse(T data, JsonResponseCode code, String msg, Long count) {
		super();
		this.data = data;
		this.code = code;
		this.msg = msg;
		this.count = count;
	}
	
	public void setError(String msg) {
        this.msg = msg;
        this.code = JsonResponseCode.ERROR;
    }
	
	public static <T> JsonResponse<List<T>> ok(IPage<T> page, String msg) {
		return new JsonResponse<List<T>>(page.getRecords(), JsonResponseCode.SUCCESS, msg, page.getTotal());
	}
	
	public static <T> JsonResponse<T> ok(String msg) {
		return new JsonResponse<T>(null, JsonResponseCode.SUCCESS, (msg == null || "".equals(msg.trim())) ? "请求成功！" : msg, null);
	}
	
	public static <T> JsonResponse<T> ok(T data, String msg) {
		return new JsonResponse<T>(data, JsonResponseCode.SUCCESS, msg, (data instanceof Collection<?>) ? ((Collection<?>)data).size() : ((data instanceof Map<?, ?>) ? ((Map<?, ?>)data).size() : ((data instanceof String[]) ? ((String[])data).length : 1L)));
	}
	
	public static <T> JsonResponse<T> error(String msg) {
		return new JsonResponse<T>(null, JsonResponseCode.ERROR, (msg == null || "".equals(msg.trim())) ? "请求失败！" : msg, null);
	}
}
